<template>
    <div>
        <el-button type="primary" size="mini" plain @click="expandTree(true)">展开</el-button>
        <el-button type="primary" size="mini" plain @click="expandTree(false)">折叠</el-button>
        <br>
        <br>
        <el-tree
          highlight-current
          default-expand-all
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          :data="treeData"
          node-key="id"
          :props="propsData"
          ref="tree"
        >
        </el-tree>
    </div>
</template>
<script>
import request from '@/utils/request'
export default {
  created() {
    this.getColumnList()
  },
  data() {
    return {
      treeData: [{
        id: 0,
        name: '所有栏目',
        children: []
      }],
      propsData: {
        label: 'name',
        id: 'id',
        children: 'children'
      }
    }
  },
  methods: {
    // 通过递归，获取到树的数据
    getColumnList() {
      request.get('/cms/column').then(res => { // 先获取栏目数据列表
        var getTree = function(parentId) { // 通过递归，获取到正常的数组
          var cn = []
          for (var i = 0; i < res.content.length; i++) {
            var n = res.content[i]
            if (n.parentId === parentId) {
              n.children = getTree(n.id)
              cn.push(n)
            }
          }
          return cn
        }
        this.treeData[0].children = getTree(0)
      })
    },
    // 点击节点时，通过回调函数，获得相应结点的id，从而得到右侧表格中的数据
    handleNodeClick(data) {
      this.$emit('getListForId', data.id)
    },
    // 全部展开or收缩树的节点
    expandTree(status) {
      for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) { // 使用该length，必须先为树指定node-key作为唯一标识符
        if (status) { // 展开
          this.$refs.tree.store._getAllNodes()[i].expanded = true
        } else { // 收缩
          this.$refs.tree.store._getAllNodes()[i].expanded = false
        }
      }
    }
  }
}
</script>
